<?php

if (!session_id()) {
  session_start();
}

define('POST', 'post');
define('GET', 'get');
define('JSON', 'application/json');
define('HTML', 'text/html');

require_once (ROOT . DS . 'app' . DS . 'util.php');
require_once (ROOT . DS . 'config' . DS . 'config.php');
require_once (ROOT . DS . 'app' . DS . 'action.php');
require_once (ROOT . DS . 'app' . DS . 'controller.php');
require_once (ROOT . DS . 'app' . DS . 'response.php');

/** Check if environment is development and display errors * */
function setReporting() {
  if (DEV_ENV == true) {
    error_reporting(E_ALL);
    ini_set('display_errors', 'On');
  } else {
    error_reporting(E_ALL);
    ini_set('display_errors', 'Off');
    ini_set('log_errors', 'On');
    ini_set('error_log', ROOT . DS . 'logs' . DS . 'error.log');
  }
}

/** Check for Magic Quotes and remove them * */
function stripSlashesDeep($value) {
  $value = is_array($value) ? array_map('stripSlashesDeep', $value) : stripslashes($value);
  return $value;
}

function removeMagicQuotes() {
  if (get_magic_quotes_gpc()) {
    $_GET = stripSlashesDeep($_GET);
    $_POST = stripSlashesDeep($_POST);
    $_COOKIE = stripSlashesDeep($_COOKIE);
  }
}

/** Check register globals and remove them * */
function unregisterGlobals() {
  if (ini_get('register_globals')) {
    $array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
    foreach ($array as $value) {
      foreach ($GLOBALS[$value] as $key => $var) {
        if ($var === $GLOBALS[$key]) {
          unset($GLOBALS[$key]);
        }
      }
    }
  }
}

/** Main Call Function * */
function dispatch() {
  $url = $_GET['url'];
  $urlArray = explode("/", $url);

  $controller = $urlArray[0];
  array_shift($urlArray);
  $actionName = $urlArray[0];
  array_shift($urlArray);

  if ($actionName == "js") {
    include "jsclient.php";
  } else {
    require_once(ROOT . DS . 'app' . DS . 'controller' . DS . $controller . '.php');
    require_once(ROOT . DS . 'app' . DS . 'action' . DS . $controller . DS . $actionName . '.php');

    $controllerName = ucfirst($controller) . 'Controller';
    $actionName = ucfirst($actionName);

    $action = new $actionName();
    call_user_func_array(array($action, 'setParams'), $urlArray);
    $dispatcher = new $controllerName($action);
    $dispatcher->execute();
  }
}

setReporting();
removeMagicQuotes();
unregisterGlobals();
dispatch();
?>